import * as turf from '@turf/turf';
import * as cesium from 'cesium/Cesium'
const Cesium = cesium
const radiansPerDegree = Math.PI / 180.0; //角度转化为弧度(rad) 
const degreesPerRadian = 180.0 / Math.PI; //弧度转化为角度
class Measure {
    constructor(oneGisCesium) {
        this.oneGisCesium = oneGisCesium;
        this.viewer = oneGisCesium.viewer;
        this.draw = oneGisCesium.draw;
        this.convert = oneGisCesium.convert
    }
    drawPolygon(callback) {
        this.clear();
        let area = null;
        this.draw.createShape('tdpolygon', points => {
            area = this.getSpaceDistance(points);
            if (points.length > 2) {
                area = this.getArea(points)
                if (!callback) return;
                callback(area)
            }
        })
    }
    terrainPolygon(callback) {
        console.log(333)
        this.clear();
        let area = null;
        this.draw.createShape('polygon', (points, info) => {
            if (info) {
                if (points.length > 2) {
                    console.log(points,888999)
                    let positions=this.convert.cartesian3ToDegreesArray(points)
                    // let positions=this.convert.  cartesian3ToTurfDegrees(points)
                    console.log(positions,666999)
                    // let inpos = this.pointsInsert(points)
                    // let boxpos = this.setPoints(points)
                    // let position = inpos.concat(boxpos)
                    // let finPosition = this.unique(position)
                    // console.log(finPosition,777888)
                    // let features = this.setTin(finPosition)
                    // area = this.getTerrainArea(features)
                    if (!callback) return;
                    callback(positions)
                } else {
                    alert("请至少选取三个点")
                }

            }

        })
    }
    getTerrainArea(features) {
        let area = 0;
        for (let i = 0; i < features.length; i++) {
            let feature = features[i]
            let triangle = feature.map(item => {
                let height = this.convert.degreesToHeight(item[0], item[1])
                let point = Cesium.Cartesian3.fromDegrees(
                    item[0],
                    item[1],
                    height
                );
                return point
            })
            var totalAngle = this.angle(triangle[0], triangle[1], triangle[2]);
            var dis_temp1 = Cesium.Cartesian3.distance(triangle[0], triangle[1]);
            var dis_temp2 = Cesium.Cartesian3.distance(triangle[1], triangle[2]);
            //三角形面积计算，两边乘以夹角的正弦值的二分之一
            area += dis_temp1 * dis_temp2 * Math.abs(Math.sin(totalAngle)) * 0.5;
        }
        if (area < 1000000) {
            return (area).toFixed(4) + "平方米";
        } else {
            return (area / 1000000.0).toFixed(4) + "平方千米";
        }
    }
    //空间两点距离计算函数
    getSpaceDistance(positions) {
        var distance = 0;
        for (var i = 0; i < positions.length - 1; i++) {
            //根据笛卡尔坐标计算距离
            let distanceRelative = Cesium.Cartesian3.distance(positions[i], positions[i + 1])
            distance = distance + distanceRelative;
        }
        if (distance < 1000) {
            return (distance).toFixed(2) + "米";
        } else {
            return (distance / 1000.0).toFixed(2) + "千米";
        }
    }
    //面积计算函数，拆分三角曲面
    getArea(points) {
        var res = 0;
        //拆分三角曲面
        for (var i = 0; i < points.length - 2; i++) {
            var j = (i + 1) % points.length;
            var k = (i + 2) % points.length;
            var totalAngle = this.angle(points[i], points[j], points[k]);
            var dis_temp1 = Cesium.Cartesian3.distance(points[i], points[j]);
            var dis_temp2 = Cesium.Cartesian3.distance(points[j], points[k]);
            //三角形面积计算，两边乘以夹角的正弦值的二分之一
            res += dis_temp1 * dis_temp2 * Math.abs(Math.sin(totalAngle)) * 0.5;
        }
        if (res < 1000000) {
            return (res).toFixed(4) + "平方米";
        } else {
            return (res / 1000000.0).toFixed(4) + "平方千米";
        }

    }
    /*角度*/
    angle(p1, p2, p3) {
        var bearing21 = this.bearing(p2, p1);
        var bearing23 = this.bearing(p2, p3);
        var angle = bearing21 - bearing23;
        if (angle < 0) {
            angle += 360;
        }
        angle = angle * radiansPerDegree; //角度
        return angle;
    }
    bearing(from, to) {
        var lat1 = this.getcartographic(from).lat * radiansPerDegree;
        var lon1 = this.getcartographic(from).lon * radiansPerDegree;
        var lat2 = this.getcartographic(to).lat * radiansPerDegree;
        var lon2 = this.getcartographic(to).lon * radiansPerDegree;
        var angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2));
        if (angle < 0) {
            angle += Math.PI * 2.0;
        }
        angle = angle * degreesPerRadian; //角度
        return angle;
    }
    //笛卡尔转经纬度
    getcartographic(point) {
        var cartographic = new Cesium.Cartographic.fromCartesian(point);
        var longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
        var latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
        var heightString = cartographic.height;
        var x = {
            lon: longitudeString,
            lat: latitudeString,
            hei: heightString
        }
        return x
    }
    cartesian3ToDegrees = function (cartesian) {
        let cartographic = new Cesium.Cartographic.fromCartesian(cartesian);
        var longitude = Cesium.Math.toDegrees(cartographic.longitude);
        var latitude = Cesium.Math.toDegrees(cartographic.latitude);
        return {
            x: longitude,
            y: latitude,
            height: cartographic.height
        }
    }
    setPoints(points) {
        let positions = points.map(item => {
            return this.convert.cartesian3ToTurfDegrees(item)
        })
        let line = turf.lineString(positions);
        let polypos = positions
        polypos.push(positions[0])
        let poly = turf.polygon([polypos]);
        this.polygon = poly
        var bbox = turf.bbox(line);
        let xarr = this.insertPos(bbox[0], bbox[2])
        let yarr = this.insertPos(bbox[1], bbox[3])
        //插值构造点阵
        let position = []
        for (let i = 0; i < xarr.length; i++) {
            for (let j = 0; j < yarr.length; j++) {
                let points = {
                    x: xarr[i],
                    y: yarr[j]
                }
                position.push(points)
            }
        }
        //筛选绘制范围内的点
        let inpos = position.filter(item => {
            var pt = turf.point([item.x, item.y]);
            if (turf.booleanPointInPolygon(pt, poly)) {
                return item
            }
        })
        let finaPos = inpos.map(el => {
            let pos = [el.x, el.y]
            return pos
        })
        return finaPos
    }
    insertPos(start, end) {
        let pos = [];
        for (let i = start; i < end; i = i + 0.0005) {
            if (i > start && i < end) {
                pos.push(i)
            }
        }
        return pos
    }
    //端点插值
    pointsInsert(points) {
        let posarr = []
        points.push(points[0])
        for (let i = 0; i < points.length - 1; i++) {
            let start = points[i]
            let end = points[i + 1]
            let dis = Cesium.Cartesian3.distance(start, end)
            let count = Math.round(dis / 20)
            for (let j = 0; j <= count; j++) {
                var cart = Cesium.Cartesian3.lerp(start, end, j / count, new Cesium.Cartesian3());
                let point = this.convert.cartesian3AddHeight(cart)
                let pos = this.convert.cartesian3ToTurfDegrees(point)
                posarr.push(pos)
            }
        }
        return posarr
    }
    //数组去重
    unique(arr) {
        for (let i = 0, len = arr.length; i < len; i++) {
            for (let j = i + 1; j < len; j++) {
                if (arr[i].toString() == arr[j].toString()) {
                    arr.splice(j, 1);
                    len--;
                    j--;
                }
            }
        }
        return arr
    }
    setTin(positions) {
        positions = positions.filter(item => {
            return !item.includes(NaN)
        })
        let points = positions.map(item => {
            let point = turf.point(item)
            return point
        })
        let pointsCollection = turf.featureCollection(points);
        let tin = turf.tin(pointsCollection)
        //去除区域外的三角面
        let feature = tin.features.filter(el => {
            let center = turf.centerOfMass(el);
            if (turf.booleanPointInPolygon(center, this.polygon)) {
                return el
            }
        })
        let features = feature.map(el => {
            let position = el.geometry.coordinates[0]
            return position
        })
        return features
    }
    clear() {
        this.draw.clear();
    }
}


export default Measure